package com.poxz.algorithm.template;

/**
 * 字符串算法
 *
 * @author poxz
 */
public class StringOps {

    /**
     * KMP 算法
     *
     * @param s 文本串
     * @param p 模式串
     */
    static void kmp(String s, String p) {
        int n = s.length(), m = p.length();
        char[] text = (' ' + s).toCharArray();
        char[] pattern = (' ' + p).toCharArray();

        int[] ne = new int[m + 1];
        for (int i = 2, j = 0; i <= m; i++) {
            while (j > 0 && pattern[i] != pattern[j + 1]) {
                j = ne[j];
            }
            if (pattern[i] == pattern[j + 1]) {
                j++;
            }
            ne[i] = j;
        }

        System.out.print("匹配位置: ");
        for (int i = 1, j = 0; i <= n; i++) {
            while (j > 0 && text[i] != pattern[j + 1]) {
                j = ne[j];
            }
            if (text[i] == pattern[j + 1]) {
                j++;
            }
            if (j == m) {
                System.out.print((i - m) + " ");
                j = ne[j];
            }
        }
        System.out.println();
    }

    /**
     * Java 字符串 API示例
     */
    static void stringAPI() {
        String s = "Hello World";

        System.out.println("长度: " + s.length());
        System.out.println("第0个字符: " + s.charAt(0));
        System.out.println("子串[0,5): " + s.substring(0, 5));

        String[] parts = s.split(" ");
        System.out.println("分割: " + java.util.Arrays.toString(parts));

        System.out.println("替换: " + s.replace("World", "Java"));
        System.out.println("小写: " + s.toLowerCase());
        System.out.println("大写: " + s.toUpperCase());
        System.out.println("去空格: '" + "  abc  ".trim() + "'");
        System.out.println("包含World? " + s.contains("World"));
        System.out.println("以Hello开头? " + s.startsWith("Hello"));
        System.out.println("以World结尾? " + s.endsWith("World"));

        char[] chars = s.toCharArray();
        System.out.println("转字符数组: " + java.util.Arrays.toString(chars));

        StringBuilder sb = new StringBuilder();
        sb.append("Hello");
        sb.append(" ");
        sb.append("World");
        System.out.println("StringBuilder: " + sb.toString());
    }

    /**
     * 功能测试
     *
     * @param args 命令行参数
     */
    public static void main(String[] args) {
        System.out.println("=== 字符串算法示例 ===\n");

        String text = "abcabcabc";
        String pattern = "abcab";
        System.out.println("文本: " + text);
        System.out.println("模式: " + pattern);
        kmp(text, pattern);
        System.out.println();

        stringAPI();
    }
}
